package com.adk.backend.service.impl;

import com.adk.backend.common.PageResult;
import com.adk.backend.entity.LxContainerList;
import com.adk.backend.mapper.ContainerMapper;
import com.adk.backend.service.ContainerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 集装箱服务实现类
 */
@Slf4j
@Service
public class ContainerServiceImpl extends ServiceImpl<ContainerMapper, LxContainerList> implements ContainerService {
    
    @Autowired
    private ContainerMapper containerMapper;
    
    @Override
    public PageResult<Map<String, Object>> getContainerList(Map<String, Object> params) {
        Integer pageNum = (Integer) params.getOrDefault("pageNum", 1);
        Integer pageSize = (Integer) params.getOrDefault("pageSize", 20);
        
        // 计算偏移量
        Integer offset = (pageNum - 1) * pageSize;
        params.put("offset", offset);
        params.put("pageSize", pageSize);
        
        // 查询总数
        Long total = containerMapper.countContainerList(params);
        
        // 查询列表
        List<Map<String, Object>> list = containerMapper.selectContainerListWithInfo(params);
        
        PageResult<Map<String, Object>> result = new PageResult<>();
        result.setList(list);
        result.setTotal(total);
        result.setPageNum(pageNum);
        result.setPageSize(pageSize);
        result.setTotalPages((int) Math.ceil((double) total / pageSize));
        
        return result;
    }
    
    @Override
    public LxContainerList getContainerById(Long id) {
        return containerMapper.selectById(id);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public LxContainerList createContainer(LxContainerList container) {
        if (container.getAddTime() == null) {
            container.setAddTime((int) (System.currentTimeMillis() / 1000));
        }
        containerMapper.insert(container);
        return container;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateContainer(LxContainerList container) {
        if (container.getUpdateTime() == null) {
            container.setUpdateTime((int) (System.currentTimeMillis() / 1000));
        }
        return containerMapper.updateById(container) > 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteContainer(Long id) {
        return containerMapper.deleteById(id) > 0;
    }
}

